import api from '@/store/api';
import i18n from '@/i18n';
import { ReturnGetters, ActionContext } from '@/types/store';

const state = {
  solSwitchStatus: true,
  cpuSwitchStatus: true,
};
type State = typeof state;

const getters = {
  solSwitchStatus: (state: State) => state.solSwitchStatus,
  cpuSwitchStatus: (state: State) => state.cpuSwitchStatus,
};
type Getters = ReturnGetters<typeof getters>;

const mutations = {
  setSolSwitchState: (state: State, SolSwitch: any) =>
    (state.solSwitchStatus = SolSwitch),
  setCpuSwitchState: (state: State, CpuSwitch: any) =>
    (state.cpuSwitchStatus = CpuSwitch),
};
type Multations = keyof typeof mutations;

const actionsNames = [
  'getSolSwitchStatus',
  'saveSolSwitchState',
  'saveCpuSwitchState',
] as const;
type ActionNames = typeof actionsNames[number];

const actions = {
  async getSerialSwitchStatus({
    commit,
  }: ActionContext<ActionNames, Multations, State, Getters>) {
    return await api
      .get('/redfish/v1/Managers/bmc/oem/serial-switch')
      .then((response) => {
        const state = response.data;
        commit('setSolSwitchState', state.SolSwitch);
        commit('setCpuSwitchState', state.CpuSwitch);
      })
      .catch((error) => console.log(error));
  },
  async saveSolSwitchState(
    { commit }: ActionContext<ActionNames, Multations, State, Getters>,
    state: any
  ) {
    const setState = {
      SolSwitch: state,
    };
    commit('setSolSwitchState', state);
    return await api
      .patch('/redfish/v1/Managers/bmc/oem/serial-switch', setState)
      .then(() => {
        if (state) {
          return i18n.t('pageSerialOverLan.toast.successSOLEnabled');
        } else {
          return i18n.t('pageSerialOverLan.toast.successSOLDisabled');
        }
      })
      .catch((error) => {
        console.log(error);
        commit('setSolSwitchState', !state);
      });
  },
  async saveCpuSwitchState(
    { commit }: ActionContext<ActionNames, Multations, State, Getters>,
    state: any
  ) {
    commit('setCpuSwitchState', state);
    const setState = {
      CpuSwitch: state,
    };
    return await api
      .patch('/redfish/v1/Managers/bmc/oem/serial-switch', setState)
      .then(() => {
        if (state) {
          return i18n.t('pageSerialOverLan.toast.successCPU0Enabled');
        } else {
          return i18n.t('pageSerialOverLan.toast.successCPU1Enabled');
        }
      })
      .catch((error) => {
        console.log(error);
        commit('setCpuSwitchState', !state);
      });
  },
};

const SertialOverLanStore = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
export default SertialOverLanStore;
